package com.polito.mad.bikeponyapp.util;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map.Entry;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContentValues;
import android.net.Uri;
import android.net.Uri.Builder;
import android.os.AsyncTask;

public class AsyncTaskForResultMessage extends AsyncTask<ContentValues, Void, ResultMessage>{

	private OnTaskCompletionListener completionListener;
	private String url;
	private boolean post;
	public AsyncTaskForResultMessage(String url,boolean post,OnTaskCompletionListener completionListener) {
		this.completionListener= completionListener;
		this.url=url;
		this.post=post;
	}
	@Override
	protected ResultMessage doInBackground(ContentValues... params) {
		if(params.length!=1)
			return null;
		ContentValues parameters = params[0];
		InputStream is =null;
		OutputStream os = null;
		HttpURLConnection connection=null;
		ResultMessage resultMessage=null;
		try 
		{
			try
			{
				if(post)
				{
					URL url_ = new URL(url);
					connection = (HttpURLConnection) url_.openConnection();
					connection.setDoInput(true);
					connection.setDoOutput(true);
					connection.setAllowUserInteraction(true);
					connection.connect();
					StringBuilder sb = new StringBuilder();
					String prefix = "";
					Iterator<String> keysIterator =  parameters.keySet().iterator();
					while(keysIterator.hasNext())
					{
						String key = keysIterator.next();
						Object value = parameters.get(key);
						sb.append(prefix).append(key).append("=").append(value.toString());
						prefix="&";
					}
					os = connection.getOutputStream();
					if(os!=null)
					{
						BufferedOutputStream bos = new BufferedOutputStream(os);
						bos.write(sb.toString().getBytes());
						bos.close();
						is = connection.getInputStream();
					}
					
				}else
				{
					Builder builder = new Uri.Builder();
					builder.encodedPath(url);
					for(Entry<String,Object> param : parameters.valueSet())
					{
						builder.appendQueryParameter(param.getKey(), param.getValue().toString());
					}
					URL url_ = new URL(builder.build().toString());
					connection = (HttpURLConnection)url_.openConnection();
					is = connection.getInputStream();
				}
				
				if(is!=null)
				{
					BufferedReader br = new BufferedReader(new InputStreamReader(is));
					String line = null;
					StringBuilder sb = new StringBuilder();
					while((line = br.readLine())!=null)
						sb.append(line);
					
					br.close();
					JSONObject result = new JSONObject(sb.toString());
					resultMessage = new ResultMessage(result);
				}
			
			}finally
			{
				connection.disconnect();
				if(os!=null)
					os.close();
			}
			return resultMessage;
		}
		catch (IOException ie)
		{
			ie.printStackTrace();
			return new ResultMessage(ResultMessage.STATUS_ERR_UNKNOWN, "The operation cannot be completed. Check your network connection");
		}catch (JSONException e) {
			e.printStackTrace();
			return new ResultMessage(ResultMessage.STATUS_ERR_UNKNOWN, "The operation cannot be completed. The server is not available");
		}
	}
	
	protected ResultMessage postProcessResult(ResultMessage resultMessage)
	{
		return resultMessage;
	}
	
	@Override
	protected void onPostExecute(ResultMessage result)
	{
		if(this.completionListener!=null)
			completionListener.onTaskEnded(result);
	}
	
	public interface OnTaskCompletionListener
	{
		public void onTaskEnded(ResultMessage resultMessage);
	}
	@Override
	protected void onCancelled() {
		onPostExecute(null);
	}
}

